<?php

namespace App\Http\Controllers\Auth\Admin;

use App\Http\Controllers\Admin\Traits\AdminTrait;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\LoginRequest;
use App\Http\Requests\Admin\BaseRequest;
use App\Log\LoginLog;
use App\Models\Admin\AdminOperateModule;
use App\Models\Admin\AdminUser;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Auth,Session;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AdminTrait;

    protected $auth;

    public function __construct()
    {
        $this->auth = Auth::guard('admin');
    }

    public function test(){
        echo '123';
    }
    //获取code
    public function info(BaseRequest $request)
    {
        if(Session::has('code')){
            $str = Session::get('code');
        }else{
            $str = $this->str_rand();
            Session::put('code',$str);
        }
        $data=[
          'code'=>  $str,
        ];
        return $this->success($data);
    }

    //登录
    public function login(LoginRequest $request)
    {
      //  echo Hash::make('123456');exit;
        $code = $request->code;
        $str = $this->str_rand();
        $data_err=[
            'code'=>$str,
        ];
        if (!$code || ($code != Session::get('code') && $code != 'MobileVersion')){

            Session::put('code',$str);
            return $this->error(['-1','code参数错误',$data_err]);
        }
        $remember = $request->remember ? true : false;
        $data = $request->only(['username','password']);
        $token = $this->auth->attempt($data);


        if (!$token){
            $str = $this->str_rand();
            Session::put('code',$str);
            $data_err=[
                'code'=>$str,
            ];
            return $this->error(['60002','账号或密码错误',$data_err]);
        }
        $data['status']=1;
        $token = $this->auth->attempt($data);
        if (!$token){
            $str = $this->str_rand();
            Session::put('code',$str);
            $data_err=[
                'code'=>$str,
            ];
            return $this->error(['60002','账号已被禁用',$data_err]);
        }
        Session::forget('code');
        $id=$this->auth->user()->id;
        $name=$this->auth->user()->name;
        //记录日志
        $this->addLog(['id'=>$id,'name'=>$name],['id'=>$id,'name'=>$name],9);
        return $this->respondWithToken($token);
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'errcode' => 0,
            'data' => array(
                'token'=>'Bearer ' . $token,
                'expires_in' => $this->auth->factory()->getTTL() * 60
            ),
            'errmsg' => 'ok',
        ]);
    }

    /**
     * Refresh a token.
     * 刷新token，如果开启黑名单，以前的token便会失效。
     * 值得注意的是用上面的getToken再获取一次Token并不算做刷新，两次获得的Token是并行的，即两个都可用。
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken($this->auth->refresh());
    }

    /**
     * 处理用户登出逻辑
     */
    public function logout(BaseRequest $request)
    {
        dd('end...');
        $this->auth->logout();
        return $this->success();
    }

    //修改密码
    public function changePassword(BaseRequest $request)
    {
        $input=$request->input();
        //过滤数据
        $rules=[
            'old_pwd'=>'required',
            'new_pwd'=>'required|alpha_num|different:old_pwd',
        ];
        $msg=[
            'alpha_num'=>'密码必须为数字或字母',
            'different'=>'新密码不能与原密码相同',
        ];
        $validator = Validator::make($input,$rules,$msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $new_pwd=$input['new_pwd'];
        if(strpos($new_pwd,' ')!==false)
        {
            return $this->error(['-1','密码不能包含空格']);
        }
        if(strlen($new_pwd)<6 || strlen($new_pwd)>20)
        {
            return $this->error(['-1','密码长度必须在6到20之间']);
        }
        //判断旧密码是否正确
        $user_id=$this->auth->user()->id;
        $old_pwd_db=AdminUser::where('id',$user_id)->value('password');
        $flag = Hash::check($input['old_pwd'],$old_pwd_db);
        if(!$flag)
        {
            return $this->error(['-1','原密码输入错误']);
        }
        $password=Hash::make($new_pwd);
        $data=[
            'password'=>$password,
        ];
        if(AdminUser::where('id',$user_id)->update($data))
        {
            return $this->success();
        }
        return $this->error();
    }

    public function addLog($pre,$next,$type,$method='')
    {
        $info = AdminOperateModule::where('pid',8)->where('type',$type)->where('model','admin_user')->when($method,function ($query)use ($method){
            $query->where('method',$method);
        })->first();
        if (!empty($info)){
            $adminLog = new LoginLog($pre,$next,$info);
            $adminLog->addLog();
        }
    }
}
